IO Byte and Character Streams
class ImageCopy{
public static void main(String[] paras){
FileInputStream in = new FileInputStream("image.jpg");
FileOutputStream out = new FileOutputStream("copy.jpg");
int byteData;
while ((byteData = in.read()) != -1) {
out.write(byteData);
}
in.close();
out.close();
}
}
Character Stream
Used for: Handling character data (text files).
class CopyFile{
public static void main(String[] ooo){
FileReader reader = new FileReader("text.txt");
FileWriter writer = new FileWriter("copy.txt");
int charData;
while ((charData = reader.read()) != -1) {
writer.write(charData);
}
reader.close();
writer.close();
}
}
| Feature | Byte Stream | Character Stream |
|---|---|---|
| Data Type | Binary data | Text/Character data |
| Size per unit | 1 byte | 2 bytes (Unicode) |
| Encoding | No encoding awareness | Aware of character encoding |
| Base Classes | InputStream, OutputStream | Reader, Writer |
| Example Use | Image, audio, PDF files | .txt, .csv, .xml files |